package com.csust.zerocode.langgraph4j.node;

import com.csust.zerocode.ai.AiCodeGenTypeRoutingService;
import com.csust.zerocode.ai.AiCodeGenTypeRoutingServiceFactory;
import com.csust.zerocode.langgraph4j.state.WorkflowContext;
import com.csust.zerocode.model.enums.CodeGenTypeEnum;
import com.csust.zerocode.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.bsc.langgraph4j.action.AsyncNodeAction;
import org.bsc.langgraph4j.prebuilt.MessagesState;

import static org.bsc.langgraph4j.action.AsyncNodeAction.node_async;

@Slf4j
public class RouterNode {
    public static AsyncNodeAction<MessagesState<String>> create() {
        return node_async(state -> {
            WorkflowContext context = WorkflowContext.getContext(state);
            log.info("执行节点: 智能路由");
            String originalPrompt = context.getOriginalPrompt();
            // TODO: 实际执行智能路由逻辑
            CodeGenTypeEnum codeGenTypeEnum = null;
            try {
                // 获取AI路由服务工厂并创建新的路由服务实例
                AiCodeGenTypeRoutingServiceFactory factory = SpringContextUtil.getBean(AiCodeGenTypeRoutingServiceFactory.class);
                AiCodeGenTypeRoutingService aiCodeGenTypeRoutingService = factory.createAiCodeGenTypeRoutingService();
                codeGenTypeEnum = aiCodeGenTypeRoutingService.routeCodeGenType(originalPrompt);
            } catch (Exception e) {
                log.error("智能路由失败: {}", e.getMessage(), e);
                //降级处理
                codeGenTypeEnum = CodeGenTypeEnum.HTML;
            }
            // 更新状态
            context.setCurrentStep("智能路由");
            context.setGenerationType(codeGenTypeEnum);
            log.info("路由决策完成，选择类型: {}", codeGenTypeEnum.getText());
            return WorkflowContext.saveContext(context);
        });
    }
}
